import { Component, OnInit } from '@angular/core';
import { EChartOption } from 'echarts';
import * as moment from 'moment';
import { DataManagementService } from '../data-management.services';
import { NotificationService } from 'app/shared/service';
import { PublicService } from 'app/public/public.service';
import { MESSAGE_CHANNEL, SELECT_OPTIONS } from 'app/app.constants';
import { differenceInCalendarDays } from 'date-fns';
import { BullySubjectService } from 'app/shared/service';

@Component({
    selector: 'itmp-road-congestion-report',
    templateUrl: './road-congestion-report.component.html',
    styleUrls: ['./road-congestion-report.component.css']
})
export class RoadCongestionReportComponent implements OnInit {
    sum = '';
    startTime = null;
    endTime = null;
    startTimeRange = '';
    endTimeRange = '';
    roadSelect = null;
    updateOptions: any;
    roadOptions = [];
    includeSelect = '';
    includeOptions = [];
    intervalSelect = '';
    intervalOptions = [];
    speedSelect = null;
    speedOptions = [];
    dateRange = null;
    isEchartsShow = false;
    queryStartTime = null;
    queryEndTime = null;
    renderHeader = null; // 表头数据的数组
    listOfData = []; // 列表数据的数组
    timeRange = [];
    congestion_parcentage = [];
    pagination = null;
    options: EChartOption = {
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                splitLine: {
                    show: true
                },
                data: this.timeRange,
                axisLabel: {
                    show: true,
                    textStyle: {
                        //x轴座标文字颜色
                        color: '#fff'
                    }
                }
            }
        ],
        yAxis: {
            type: 'value',
            axisLabel: {
                show: true,
                textStyle: {
                    //x轴座标文字颜色
                    color: '#fff'
                }
            }
        },
        series: [
            {
                name: 'data',
                type: 'line',
                // stack: '总量',
                data: this.congestion_parcentage
            }
        ],
        dataZoom: [
            {
                type: 'slider',
                show: false,
                // start: 0,
                // end: 50,
                handleSize: 8
            },
            {
                type: 'inside'
                // start: 0,
                // end: 50
            }
        ]
    };
    echartsIntance: any;

    constructor(
        private DMService: DataManagementService,
        private message: NotificationService,
        private publicService: PublicService,
        private bully: BullySubjectService
    ) {}

    ngOnInit() {
        this.getRoad();
        this.intervalOptions = [{ name: '15min', id: 1 }, { name: '30min', id: 2 }, { name: '60min', id: 3 }];
        this.includeOptions = [
            { name: 'Weekday', id: '1%7C2%7C3%7C4%7C5' },
            { name: 'Weekend', id: '6%7C7' },
            { name: 'All', id: '1%7C2%7C3%7C4%7C5%7C6%7C7' }
        ];
        this.speedOptions = [{ name: '5', id: 1 }];
    }

    onChartInit(ec: any) {
        this.echartsIntance = ec;
    }

    // 获取road下拉框数据
    getRoad() {
        // this.DMService.getAllEnumInfo().subscribe(res => {
        //     if (res.code === '000000') {
        //         const data = [];
        //         res.data.forEach(ele => {
        //             if (ele.category === 'TscDetector') {
        //                 data.push(ele);
        //             }
        //         });
        //         this.roadOptions = data;
        //         this.roadSelect = data[0].name;
        //         this.getData(this.initDefaultData());
        //     }
        // });

        // 这里实际应该取VBID检测器，但是由于现阶段后台暂时没有提供。先暂时使用Tsc检测器
        const response = this.publicService.getSelectOptionsList(SELECT_OPTIONS.AID_EQUIP);
        const res = response.data;
        if (res && res.length !== 0) {
            this.roadOptions = [...res];
            if (localStorage.getItem('itmp_lang') === 'vi') {
                this.roadOptions.forEach(site => {
                    site.displayName = site.vietName;
                });
            } else {
                this.roadOptions.forEach(site => {
                    site.displayName = site.name;
                });
            }
            // this.roadSelect = res[0].name;
            this.roadSelect = res[0].displayName;
            this.getData(this.initDefaultData());
        }
        this.changeLang();
    }

    changeLang() {
        this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.LANGUAGE_CHANNEL).subscribe(res => {
            if (res.data === 'vi') {
                this.roadOptions.forEach(site => {
                    site.displayName = site.vietName;
                });
                this.roadSelect = this.roadOptions[0];
            } else {
                this.roadOptions.forEach(site => {
                    site.displayName = site.name;
                });
                this.roadSelect = this.roadOptions[0];
            }
        });
    }

    initDefaultData() {
        // 为页面加载默认数据
        // 获取当天日期
        const day1 = new Date();
        day1.setTime(day1.getTime());
        const thisDay = day1.getFullYear() + '-' + (day1.getMonth() + 1) + '-' + day1.getDate();
        // 获取明天日期
        const day3 = new Date();
        day3.setTime(day3.getTime() + 24 * 60 * 60 * 1000);
        const nextDay = day3.getFullYear() + '-' + (day3.getMonth() + 1) + '-' + day3.getDate();
        const hour = day1.getHours(); // 得到小时
        const minu = day1.getMinutes(); // 得到分钟
        const second = day1.getSeconds();
        const start = new Date(new Date(new Date().toLocaleDateString()).getTime()); // 获取当日的00:00
        const todayStart = thisDay + ` 00:00:00`;
        const todayEnd = thisDay + ` ${hour}:${minu}:${second}`;
        this.dateRange = [todayStart, todayEnd];
        this.startTime = start;
        this.endTime = new Date();
        this.includeSelect = '1%7C2%7C3%7C4%7C5%7C6%7C7';
        this.intervalSelect = '60min';
        this.speedSelect = '5';
        this.queryStartTime = thisDay;
        this.queryEndTime = this.queryStartTime;
        this.startTimeRange = '00:00:00';
        this.endTimeRange = `${hour}:${minu}:${second}`;
        this.sum = "'" + this.roadSelect.split('<')[0] + "'";
        return `startDateRange=${thisDay},endDateRange=${thisDay},startTimeRange=00:00:00,endTimeRange=${hour}:${minu}:${second},weekday=${
            this.includeSelect
        },interval=60min,threshold=5,deviceIds=${this.sum}`;
    }

    getData(queryData: string) {
        this.DMService.getRoadRep(queryData).subscribe(res => {
            if (res.messagecode === '000000') {
                // for (const item of res.data) {
                //     this.timeRange.push(item.interval_zone);
                //     this.congestion_parcentage.push(item.congestion_parcentage);
                // }
                const timeRange = `${this.startTimeRange}~${this.endTimeRange}`;
                const timeInterval = +this.intervalSelect.split('m')[0];
                const resultData = this.DMService.generateAllData(timeInterval, res.data, timeRange, 'DEVICEID');
                const detectorTypeMap = {};
                const detectorDataList = [];
                const detectorTypeList = [];
                for (const item of resultData) {
                    this.timeRange.push(item.interval_zone);

                    if (!detectorTypeMap[item.DETECTOR_ID]) {
                        detectorTypeMap[item.DETECTOR_ID] = item;
                        detectorTypeList.push(item.DETECTOR_ID);
                    }
                    // this.AVG_VOLUME.push(item.AVG_VOLUME);
                }
                detectorTypeList.forEach(detector => {
                    const newDetectorValue = {
                        name: `Detector ${detector}`,
                        type: 'line',
                        data: []
                    };
                    resultData.forEach(item => {
                        if (item.DETECTOR_ID === detector) {
                            newDetectorValue.data.push(item.congestion_parcentage);
                        } else {
                            newDetectorValue.data.push('0');
                        }
                    });
                    detectorDataList.push(newDetectorValue);
                });
                if (resultData.length === 0) {
                    this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.nodata' });
                    this.isEchartsShow = false;
                } else {
                    this.isEchartsShow = true;
                }
                // this.getOption();
                this.updateOptions = {
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: this.timeRange
                    },
                    series: [...detectorDataList]
                };
            }
            // this.echartsIntance.setOption(this.options, true);
        });
    }

    search() {
        // 判断筛选框是否完整
        if (!this.roadSelect) {
            this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.select_notify' });
            return;
        }
        if (
            this.queryStartTime === null ||
            this.queryEndTime === null ||
            this.includeSelect === null ||
            this.intervalSelect === null ||
            this.speedSelect === null
        ) {
            this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.select_notify' });
        } else {
            if (this.roadSelect instanceof Array) {
                const road = [];
                this.sum = '';
                this.roadSelect.forEach(ele => {
                    road.push(ele.split('<')[0]);
                });
                road.forEach((value, i) => {
                    // 将数组每一项加上单引号
                    road[i] = "'" + road[i] + "'";
                    this.sum += road[i];
                    if (i < road.length - 1) {
                        // 每一项中间以|隔开
                        this.sum += '%7C';
                    }
                });
            } else {
                this.sum = "'" + this.roadSelect.split('<')[0] + "'";
            }
            const a = `startDateRange=${this.queryStartTime},endDateRange=${this.queryEndTime},weekday=${this.includeSelect},deviceIds=${
                this.sum
            }`;
            const b = `startTimeRange=${this.startTimeRange},endTimeRange=${this.endTimeRange},interval=${this.intervalSelect},threshold=${
                this.speedSelect
            }`;
            const queryData = `${a},${b}`;
            this.DMService.getRoadRep(queryData).subscribe(res => {
                if (res.messagecode === '000000') {
                    this.timeRange = [];
                    // this.congestion_parcentage = [];
                    // for (const item of res.data) {
                    //     this.timeRange.push(item.interval_zone);
                    //     this.congestion_parcentage.push(item.congestion_parcentage);
                    // }
                    const timeRange = `${this.startTimeRange}~${this.endTimeRange}`;
                    const timeInterval = +this.intervalSelect.split('m')[0];
                    const resultData = this.DMService.generateAllData(timeInterval, res.data, timeRange, 'DEVICEID');
                    const detectorTypeMap = {};
                    const detectorDataList = [];
                    const detectorTypeList = [];
                    for (const item of resultData) {
                        this.timeRange.push(item.interval_zone);

                        if (!detectorTypeMap[item.DETECTOR_ID]) {
                            detectorTypeMap[item.DETECTOR_ID] = item;
                            detectorTypeList.push(item.DETECTOR_ID);
                        }
                        // this.AVG_VOLUME.push(item.AVG_VOLUME);
                    }
                    detectorTypeList.forEach(detector => {
                        const newDetectorValue = {
                            name: `Detector ${detector}`,
                            type: 'line',
                            data: []
                        };
                        resultData.forEach(item => {
                            if (item.DETECTOR_ID === detector) {
                                newDetectorValue.data.push(item.congestion_parcentage);
                            } else {
                                newDetectorValue.data.push('0');
                            }
                        });
                        detectorDataList.push(newDetectorValue);
                    });
                    if (resultData.length === 0) {
                        this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.nodata' });
                        this.isEchartsShow = false;
                    } else {
                        this.isEchartsShow = true;
                    }
                    this.updateOptions = {
                        xAxis: {
                            type: 'category',
                            boundaryGap: false,
                            data: this.timeRange
                        },
                        series: [...detectorDataList]
                    };
                    // this.getOption();
                    // this.options.xAxis[0].data = this.timeRange;
                    // this.echartsIntance.setOption(this.options, true);
                }
            });
        }
    }

    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        // tslint:disable-next-line: max-line-length
        // const param = `startDateRange=${this.queryStartTime},endDateRange=${this.queryEndTime},startTimeRange=${this.startTimeRange},endTimeRange=${this.endTimeRange},interval=60min,threshold=5`;
        // this.getData(param);
    }

    onSizeChange(e) {
        this.pagination.pageSize = e;
        // tslint:disable-next-line: max-line-length
        // const param = `startDateRange=${this.queryStartTime},endDateRange=${this.queryEndTime},startTimeRange=${this.startTimeRange},endTimeRange=${this.endTimeRange},interval=60min,threshold=5`;
        // this.getData(param);
    }

    onOk(result: Date): void {}

    onChange(result: Date): void {
        const t1 = moment(result[0]).format('YYYY-MM-DD 00:00:00');
        const t2 = moment(result[1]).format('YYYY-MM-DD 23:59:59');
        let month = t1.split(' ')[0].split('-')[1];
        let day = t1.split(' ')[0].split('-')[2];
        const year = t1.split(' ')[0].split('-')[0];
        let month1 = t2.split(' ')[0].split('-')[1];
        let day1 = t2.split(' ')[0].split('-')[2];
        const year1 = t2.split(' ')[0].split('-')[0];
        if (month.includes('0')) {
            month = month.replace(/\b(0+)/gi, '');
        }
        if (day.includes('0')) {
            day = day.replace(/\b(0+)/gi, '');
        }
        if (month1.includes('0')) {
            month1 = month1.replace(/\b(0+)/gi, '');
        }
        if (day1.includes('0')) {
            day1 = day1.replace(/\b(0+)/gi, '');
        }
        this.queryStartTime = year + '-' + month + '-' + day;
        this.queryEndTime = year1 + '-' + month1 + '-' + day1;
        this.startTimeRange = t1.split(' ')[1];
        this.endTimeRange = t2.split(' ')[1];
    }

    // public startTimeSearch() {
    //     const a = new Date(this.startTime).getTime();
    //     const startTimeRange = moment(a).format('HH:mm');
    //     this.startTimeRange = startTimeRange;
    // }
    // public endTimeSearch() {
    //     const a = new Date(this.endTime).getTime();
    //     const endTimeRange = moment(a).format('HH:mm');
    //     this.endTimeRange = endTimeRange;
    // }
    public roadSearch() {}

    public includeSearch() {}

    public intervalSearch() {}

    public speedSearch() {}

    // 禁用今天之后的日期选择
    range(start: number, end: number): number[] {
        const result: number[] = [];
        for (let i = start; i < end; i++) {
            result.push(i);
        }
        return result;
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };

    disabledDateTime: object = () => {
        return {
            nzDisabledHours: () => this.range(0, 24).splice(4, 20),
            nzDisabledMinutes: () => this.range(30, 60),
            nzDisabledSeconds: () => [55, 56]
        };
    };

    disabledRangeTime: object = (value: Date[], type: 'start' | 'end') => {
        if (type === 'start') {
            return {
                nzDisabledHours: () => this.range(0, 60).splice(4, 20),
                nzDisabledMinutes: () => this.range(30, 60),
                nzDisabledSeconds: () => [55, 56]
            };
        }
        return {
            nzDisabledHours: () => this.range(0, 60).splice(20, 4),
            nzDisabledMinutes: () => this.range(0, 31),
            nzDisabledSeconds: () => [55, 56]
        };
    };
}
